# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
# ========= 导入数据类 ==============
from basicweb.models import Department, Position,Line

def get_department_data(request):
    """获取当前产线下所有的部门"""
    # 获取默认的产线
    line = request.session.get('current_line')
    # 获取传递过来的条件
    q_str = request.POST.get('q_str')
    # 获取当前的line对象
    obj_line = Line.objects.filter(id=line).first()
    # 获取数据
    departments = list(Department.objects.filter(line_id=line).filter(Q(name__icontains=q_str)|
                                                                      Q(position__name__icontains=q_str)).distinct().values())

    # 遍历
    for index, value in enumerate(departments):
        positions = list(Position.objects.filter(department_id=value.get('id')).values())
        # 添加产线信息
        departments[index]['line_id'] = obj_line.id
        departments[index]['line_name'] = obj_line.name
        # 添加职位
        departments[index]['position'] = positions

    print(departments)

    # 传递给前端
    return JsonResponse({'data': departments})


def get_department_select(request):
    """获取某一个产线下的部门"""
    # 获取当前的产线Id
    # line_id = request.POST.get('line_id')
    line_id = request.session.get('current_line')
    # 获取当前的部门
    departments = list(Department.objects.filter(line_id=line_id).values('id', 'name'))
    # 定义容器
    department_list = []
    # 遍历
    for index, value in enumerate(departments):
        department_list.append({'name': value.get('name'), 'value': value.get('id')})
    # 返回
    return JsonResponse({'data': department_list})


def add_value(request):
    """添加部门"""
    # 获取传递过来的部门名称
    name = request.POST.get('name')
    line = request.POST.get('line')
    # 定义返回值的数据结构
    res = {'status': True}
    # 判断当前名称是否存在
    is_exists = Department.objects.filter(name__icontains=name).exists()
    if is_exists:
        res['status'] = False
        res['error'] = '当前输入的部门名称已存在！'
        return JsonResponse(res)
    try:
        Department.objects.create(name=name, line_id=line)
    except Exception as e:
        res['status'] = False
        res['error'] = '添加部门信息同步到数据库出现异常！具体原因：' + str(e)

    return JsonResponse(res)


def edit_value(request):
    """修改部门"""
    # 获取传递过来的部门名称
    department_id = request.POST.get("department_id")
    name = request.POST.get('name')
    # 定义返回值的数据结构
    res = {'status': True}
    # 判断当前名称是否存在
    is_exists = Department.objects.filter(name__icontains=name).exists()
    if is_exists:
        res['status'] = False
        res['error'] = '输入的修改后的部门名称已存在！'
        return JsonResponse(res)
    try:
        # 获取当前的部门对象
        obj = Department.objects.filter(id=department_id).first()
        # 修改
        obj.name = name
        # 保存
        obj.save()

    except Exception as e:
        res['status'] = False
        res['error'] = '修改部门信息同步到数据库出现异常！具体原因：' + str(e)

    return JsonResponse(res)


def del_value(request):
    """删除部门"""
    # 获取传递过来的部门名称
    department_id = request.POST.get("department_id")
    # 定义返回值的数据结构
    res = {'status': True}
    # 判断当前名称是否存在
    is_exists = Position.objects.filter(department_id=department_id).exists()
    if is_exists:
        res['status'] = False
        res['error'] = '当前的部门下还有职位，无法删除！'
        return JsonResponse(res)
    try:
       Department.objects.filter(id=department_id).first().delete()
    except Exception as e:
        res['status'] = False
        res['error'] = '删除部门信息同步到数据库出现异常！具体原因：' + str(e)

    return JsonResponse(res)
